﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class RadioManager : MonoSingleton<RadioManager> {

    private Sprite m_sprite;



    protected override void Init()
    {
        
        if (!Directory.Exists(Application.persistentDataPath + "ImagePath"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + "ImagePath");
        }
        if (m_sprite == null)
        {
            m_sprite = (ResourceManager.Instance.GetResource("Radio/",typeof(Image),enResourceType.UIPrefab,false).m_content as Image).sprite;
        }
    }

    public void SetImage(string url,Image image)
    {
        if (!File.Exists(Path))
        {
            StartCoroutine(DownImage(url, image));

        }
        else
        {
            StartCoroutine(loadImage(url, image));
        }


    }

    IEnumerator DownImage(string url,Image image)
    {
        //m_Image = gameObject.transform.Find("Canvas/Imagetest").GetComponent<Image>();
        WWW www = new WWW(url);
        yield return www;
        Texture2D texture = www.texture;
        byte[] ImagePNG = texture.EncodeToPNG();
        FileTools.WriteFile(Path,ImagePNG);
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
        image.sprite = sprite;
    }

    IEnumerator loadImage(string url, Image image)
    {
        string loadPath = "file:///" + Path;
        WWW www = new WWW(loadPath);
        yield return www;
        Texture2D texture = www.texture;
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
        image.sprite = sprite;
    }

    public string Path
    {
        get {
            return Application.persistentDataPath + "ImagePath";
        }
    }
}
